import React, { useState } from 'react';
import {
  Card,
  Form,
  Input,
  Select,
  Upload,
  Button,
  message,
  Typography,
  Space,
  Alert,
} from 'antd';
import {
  UploadOutlined,
  InboxOutlined,
} from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
import { uploadTorrent } from '../../api/torrent';

const { Title, Text } = Typography;
const { TextArea } = Input;
const { Option } = Select;
const { Dragger } = Upload;

const TorrentUpload: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [torrentFile, setTorrentFile] = useState<File | null>(null);
  const navigate = useNavigate();

  const categories = [
    { value: '电影', label: '电影' },
    { value: '电视剧', label: '电视剧' },
    { value: '音乐', label: '音乐' },
    { value: '软件', label: '软件' },
    { value: '游戏', label: '游戏' },
    { value: '电子书', label: '电子书' },
    { value: '动漫', label: '动漫' },
    { value: '其他', label: '其他' },
  ];

  const beforeUpload = (file: File) => {
    const isTorrent = file.name.toLowerCase().endsWith('.torrent');
    if (!isTorrent) {
      message.error('只能上传.torrent格式的文件!');
      return false;
    }
    
    const isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.error('种子文件大小不能超过10MB!');
      return false;
    }

    setTorrentFile(file);
    return false; // 防止自动上传
  };

  const handleSubmit = async (values: any) => {
    if (!torrentFile) {
      message.error('请选择要上传的种子文件');
      return;
    }

    try {
      setLoading(true);
      
      const formData = new FormData();
      formData.append('file', torrentFile);
      formData.append('title', values.title);
      formData.append('description', values.description || '');
      formData.append('category', values.category);

      const response = await uploadTorrent(formData);
      
      if (response.code === 200) {
        message.success('种子上传成功，等待管理员审核');
        navigate('/torrents');
      } else {
        message.error(response.message || '上传失败');
      }
    } catch (error) {
      console.error('上传失败:', error);
      message.error('上传失败，请稍后重试');
    } finally {
      setLoading(false);
    }
  };

  const uploadProps = {
    name: 'file',
    multiple: false,
    beforeUpload,
    onRemove: () => {
      setTorrentFile(null);
    },
    fileList: torrentFile ? [{
      uid: '1',
      name: torrentFile.name,
      status: 'done' as const,
    }] : [],
  };

  return (
    <div style={{ maxWidth: 800, margin: '0 auto' }}>
      <Card>
        <Title level={2}>
          <UploadOutlined /> 上传种子
        </Title>
        
        <Alert
          message="上传须知"
          description={
            <ul style={{ margin: 0, paddingLeft: 20 }}>
              <li>只接受.torrent格式的文件</li>
              <li>种子文件大小不能超过10MB</li>
              <li>上传的种子需要等待管理员审核</li>
              <li>请确保资源内容合法，违规内容将被删除</li>
              <li>建议上传高质量、稀缺的资源</li>
            </ul>
          }
          type="info"
          showIcon
          style={{ marginBottom: 24 }}
        />

        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            label="种子文件"
            required
          >
            <Dragger {...uploadProps}>
              <p className="ant-upload-drag-icon">
                <InboxOutlined />
              </p>
              <p className="ant-upload-text">
                点击或拖拽文件到此处上传
              </p>
              <p className="ant-upload-hint">
                仅支持.torrent格式文件，大小不超过10MB
              </p>
            </Dragger>
          </Form.Item>

          <Form.Item
            label="种子标题"
            name="title"
            rules={[
              { required: true, message: '请输入种子标题' },
              { min: 5, message: '标题至少5个字符' },
              { max: 200, message: '标题最多200个字符' }
            ]}
          >
            <Input
              placeholder="请输入详细的种子标题，包含资源信息"
              showCount
              maxLength={200}
            />
          </Form.Item>

          <Form.Item
            label="资源分类"
            name="category"
            rules={[{ required: true, message: '请选择资源分类' }]}
          >
            <Select placeholder="请选择资源分类">
              {categories.map(cat => (
                <Option key={cat.value} value={cat.value}>
                  {cat.label}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            label="种子描述"
            name="description"
            rules={[
              { max: 2000, message: '描述最多2000个字符' }
            ]}
          >
            <TextArea
              rows={6}
              placeholder="请详细描述资源内容，包括画质、音质、字幕等信息..."
              showCount
              maxLength={2000}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button
                type="primary"
                htmlType="submit"
                loading={loading}
                disabled={!torrentFile}
              >
                上传种子
              </Button>
              <Button onClick={() => navigate('/torrents')}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  );
};

export default TorrentUpload; 